package com.ch.ebusiness.service.before.impl;

import com.ch.ebusiness.entity.BUser;
import com.ch.ebusiness.repository.before.UserRepository;
import com.ch.ebusiness.service.before.UserService;
import com.ch.ebusiness.util.CommonUtils;
import com.ch.ebusiness.util.Constant;
import com.ch.ebusiness.util.RedisUtils;
import com.ch.ebusiness.util.ResultEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    
    @Resource
    private RedisUtils redisUtils;
    
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    
    @Resource
    private UserRepository userRepository;
    
    @Override
    public String isUse(BUser bUser) {
        if (userRepository.isUse(bUser).size() > 0) {
            return "no";
        }
        return "ok";
    }
    
    @Override
    public String register(BUser bUser) {
        // 获取手机号
        String telephone = bUser.getPhoneNumber();
        
        // 拼接为redis存放的key
        String key = "REDIS_CODE" + telephone;
        
        // 通过key寻找value（验证码）
        ResultEntity<String> resultEntity = redisUtils.getRedisValueByKey(key);
        
        String result = resultEntity.getResult();
        
        
        // 判断获取redis中的验证码是否成功
        if (ResultEntity.FAILED.equals(result)) {
            return Constant.MESSAGE_CODE_INVALID;
        }
        
        // 获取redis中的验证码的值
        String redisCode = resultEntity.getData();
        
        if (redisCode == null) {
            return Constant.MESSAGE_CODE_NOT_EXIST;
        }
        
        // 获取表单提交的验证码
        String formCode = bUser.getMessageCode();
        System.out.println(formCode);
        
        // 如果redis中的验证码与表单提交的验证码不同
        if (!Objects.equals(formCode, redisCode)) {
            return Constant.MESSAGE_CODE_INVALID;
        }
        
        // 验证码比对一致，删除redis中的验证码数据
        //redisUtils.removeRedisKeyByKey(key);
        
        //对密码MD5加密
        bUser.setBpwd(bCryptPasswordEncoder.encode(bUser.getBpwd()));
        if (userRepository.register(bUser) > 0) {
            return "user/login";
        }
        return "user/register";
    }
    
    @Override
    public String login(BUser bUser, HttpSession session, Model model) {
        
        System.out.println(bUser.getPhoneNumber());
        System.out.println(bUser.getBpwd());
        //对密码MD5加密
        bUser.setBpwd(bCryptPasswordEncoder.encode("123456"));
        //String rand = (String) session.getAttribute("rand");
        //if (!rand.equalsIgnoreCase(bUser.getCode())) {
        //    model.addAttribute("errorMessage", "验证码错误！");
        //    return "user/login";
        //}
        List<BUser> list = userRepository.login(bUser);
        if (list.size() > 0) {
            session.setAttribute("bUser", list.get(0));
            System.out.println(session.getAttribute("bUser"));
            return "redirect:/";//到首页
        }
        model.addAttribute("errorMessage", "用户名或密码错误！");
        return "user/login";
    }
    
    
    @Override
    public String sendShortMessage(String phoneNumber) {
        
        
        // 调用工具类中的发送验证码的方法，可以从配置文件中读取配置的接口信息
        ResultEntity<String> sendResultEntity = CommonUtils.sendShortMessage(phoneNumber);
        
        // 判断-发送成功
        if (ResultEntity.SUCCESS.equals(sendResultEntity.getResult())) {
            
            // 得到ResultEntity中的验证码
            String code = sendResultEntity.getData();
            
            // 将验证码存入到redis中（设置TTL，这里设置为5分钟）
            ResultEntity<String> redisResultEntity = redisUtils.setRedisKeyValueWithTimeout(
                    "REDIS_CODE" + phoneNumber, code, 5, TimeUnit.MINUTES);
            
            // 判断存入redis是否成功
            if (ResultEntity.SUCCESS.equals(redisResultEntity.getResult())) {
                // 存入成功，返回成功
                return "ok";
            } else {
                // 存入失败，返回redis返回的ResultEntity
                System.out.println(redisResultEntity.getMessage());
                return redisResultEntity.getMessage();
            }
        } else {
            // 发送验证码失败，返回发送验证码的ResultEntity
            System.out.println(sendResultEntity.getMessage());
            return sendResultEntity.getMessage();
        }
    }
    
}
